<?php
/**
 * Description of UTM
 *
 * @author decws
 */
class Model_UTM {

	public static function instance() {
		if(isset($_SERVER["HTTP_REFERER"]) && !strstr($_SERVER["HTTP_REFERER"], "http://www.buscadescontos.com.br") && !strstr($_SERVER["HTTP_REFERER"], "http://buscadescontos.com.br") && !strstr($_SERVER["HTTP_REFERER"], "http://admin.buscadescontos.net.br")) {
			Session::instance()->set("http_referer", $_SERVER["HTTP_REFERER"]);
		}
		
		Model_UTM::detect_search();
		$utm_params = array(
			"utm_source" => "utm_source",
			"src" => "utm_source",
			"utm_medium" => "utm_medium",
			"medium" => "utm_medium",
			"utm_campaign" => "utm_campaign",
			"campaign" => "utm_campaign",
			"utm_term" => "utm_term",
			"term" => "utm_term",
			"utm_content" => "utm_content",
			"network" => "utm_network",
			"ad" => "utm_ad",
		);
		$session_utm = array();
		foreach ($utm_params as $key => $param) {
			if (isset($_GET[$key]) && !empty($_GET[$key])) {
				$session_utm[$param] = tokenizer::safe($_GET[$key]);
			}
		}
		Session::instance()->set("utm", $session_utm);
		return new Model_UTM();
	}

	public function get_serialized() {
		$return = "";
		if (isset($_SESSION["utm"]) && is_array($_SESSION["utm"])) {
			$separator = "";
			foreach ($_SESSION["utm"] as $var => $value) {
				$return.= $separator . $var . "=" . $value;
				$separator = "&";
			}
		}
		return $return;
	}
	
	public function as_array() {
		$return = array();
		if (isset($_SESSION["utm"]) && is_array($_SESSION["utm"])) {
			foreach ($_SESSION["utm"] as $var => $value) {
				$return[$var] = $value;
			}
		}
		return $return;
	}
    
	public static function check_utm($utm,$value) {
		if(isset($_SESSION["utm"]) && $value==$_SESSION["utm"][$utm]) {
			return true;
		}
		return false;
	}

	public static function detect_search() {
		if(Session::instance()->get("http_referer", false)){
			if (preg_match('/google\.com[\.br]*\/[search|#|m|url].*[&|?]q\=([^&]+)/', Session::instance()->get("http_referer"), $matches)) {
				$_GET["utm_source"] = "google";
				$_GET["utm_term"] = $matches[1];
				$_GET["utm_medium"] = "organic";
			}else
			if (preg_match('/bing\.com\/search\?q\=([^&]+)/', Session::instance()->get("http_referer"), $matches)) {
				$_GET["utm_source"] = "bing";
				$_GET["utm_term"] = $matches[1];
				$_GET["utm_medium"] = "organic";
			}else
			if (preg_match('/search\.yahoo\.com\/search.*[&|?]p\=([^&]+)/', Session::instance()->get("http_referer"), $matches)) {
				$_GET["utm_source"] = "yahoo";
				$_GET["utm_term"] = $matches[1];
				$_GET["utm_medium"] = "organic";
			}
		}
	}

} // End Utm